package com.chonglie;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;

public class MediaPlayerActivity extends Activity {

	private MediaPlayer mediaPlayer;

	private SeekBar seekBar;

	private boolean isChanging = false;

	private Timer timer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mediaplayer);

		mediaPlayer = MediaPlayer.create(this, R.raw.music_01);
		seekBar = (SeekBar) findViewById(R.id.mediaplayer_seekbar_music);
		seekBar.setMax(mediaPlayer.getDuration());
		seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub

			}

			public void onStartTrackingTouch(SeekBar seekBar) {
				isChanging = true;
			}

			public void onStopTrackingTouch(SeekBar seekBar) {
				if (mediaPlayer.isPlaying()) {
					mediaPlayer.seekTo(seekBar.getProgress());
				}
				isChanging = false;
			}

		});

		timer = new Timer();
		TimerTask task = new TimerTask() {

			@Override
			public void run() {

				if (isChanging) {
					return;
				}

				if (mediaPlayer.isPlaying()) {
					seekBar.setProgress(mediaPlayer.getCurrentPosition());
				}

			}
		};

		timer.schedule(task, 0, 50);

	}

	public void onMusicStartClick(View view) {
		mediaPlayer.reset();

		mediaPlayer = MediaPlayer.create(this, R.raw.music_01);
		mediaPlayer
				.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

					public void onCompletion(MediaPlayer mp) {
						// Toast.makeText(this, R.string.COMMON_BTN_STOP, 1000);
						mediaPlayer.stop();
					}
				});
		try {
			mediaPlayer.prepare();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mediaPlayer.start();
	}

	public void onMusicStopClick(View view) {
		mediaPlayer.stop();
		seekBar.setProgress(0);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		timer.cancel();
		timer = null;
	}

}
